﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Transactions;

public partial class WebForm_EmpData : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            gv.DataBind();
            //gv2.DataBind();
        }
    }

    protected void fv_ItemCommand(object sender, FormViewCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "MyCancel":
                gv.DataBind();
                break;
        }
    }

    protected void fv_Saved(object sender, EventArgs e)
    {
        MyObj.ShowMessage("Form", "msgSaveOK");

        gv.DataBind();
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        mv.SetActiveView(mvForm);
        fv.ChangeMode(FormViewMode.Insert);
        fv.DataBind();
    }

    protected void gv_ItemCommand(object sender, GridViewCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "MyEdit":
                {
                    var row = (e.CommandSource as Control).NamingContainer as GridViewRow;

                    var db = new DB();
                    var dt = db.Execute("SELECT * FROM EmpData WHERE EmpID = @EmpID"
                                    , new DBParameter("EmpID", gv.DataKeys[row.RowIndex]["EmpID"]));

                    mv.SetActiveView(mvForm);
                    fv.ChangeMode(FormViewMode.Edit);
                    fv.DataSource = dt;
                    fv.DataBind();
                }

                break;
            case "MyDelete":
                {
                    var row = (e.CommandSource as Control).NamingContainer as GridViewRow;

                    if (DelData(row) == true)
                    {
                        gv.DataBind();
                    }
                }

                break;
        }
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        gv.DataBind();
    }

    protected bool DelData(GridViewRow row)
    {
        using (TransactionScope scope = new TransactionScope())
        {
            var db = new DB();

            db.ExecuteNonQuery("DELETE FROM EmpData WHERE EmpID = @EmpID "
                , new DBParameter("EmpID", gv.DataKeys[row.RowIndex]["EmpID"]));

            scope.Complete();
        }

        return true;
    }
}